package ro.bean;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Demo implements PropertyChangeListener{

	static final String fileName = "test.tmp";
	
	public void propertyChange(PropertyChangeEvent e){
		System.out.println("Property " + e.getPropertyName()
				+ " changed from "+ e.getOldValue() + " to "+ e.getNewValue());
	}
	
	public static void main(String[] args){
		Point p1 = new Point();
		p1.addPropertyChangeListener(new Demo());
		System.out.println("p1 = "+ p1);
		p1.setRectangular(5, 2);
		System.out.println("p1 = "+ p1);
		p1.setX( 6 );
		p1.setY( 3 );
		System.out.println("p1 = "+ p1);
		p1.offset(6, 4);
		System.out.println("p1 = "+ p1);
		save(p1, fileName);
		Point p2 = (Point) restore(fileName);
		System.out.println("Had: "+p1);
		System.out.println("Got: "+ p2);
	}
	
	static void save(Serializable p, String fn){
		try{
			System.out.println("Writing to file: "+ p);
			FileOutputStream fo = new FileOutputStream(fn);
			ObjectOutputStream so = new ObjectOutputStream(fo);
			so.writeObject(p);
			so.flush();
		} catch(Exception e){
			System.out.println(e);
			System.exit(1);
		}
	}
	
	static Object restore(String fn){
		try{ 
			Object result;
			System.out.println("Reading from file: "+fn);
			FileInputStream fi = new FileInputStream(fn);
			ObjectInputStream si = new ObjectInputStream(fi);
			return si.readObject();
		}catch(Exception e) {
			System.out.println(e);
			System.exit(1);
		}
		return null;
	}
}
